###############################
# Figure 1 and Tables A3-A5
###############################

rm(list=ls())

# load packages 
library(foreign)
library(lmtest)
library(sandwich)
library(stargazer)
library(msm)
library("readxl")
library(cregg)
library("ggplot2")
library(gridExtra)
library(readstata13)
library(Hmisc)

##############################
# Prepare data
##############################

# load data
load("replication_data.Rdata")
names(d)

#######################################
# AMCE by Bureaucrat Gender
#######################################

amces4a <- cj(d, outcome_q3 ~ speed_eng + theft_eng  + partyid_eng + age_eng + education_eng, id = ~idnum, estimate = "amce", by = ~gender_eng)[c(1:4,14:17),]
amces4a$feature = c("Speed corruption", "Speed corruption", "Theft corruption", "Theft corruption","Speed corruption", "Speed corruption", "Theft corruption", "Theft corruption")
diff_amces4a <- cj(d, outcome_q3 ~ speed_eng + theft_eng + partyid_eng + age_eng + education_eng, id = ~idnum, estimate = "amce_diff", by = ~gender_eng)[7:8,]
diff_amces4a$feature = c("Speed corruption", "Theft corruption")
plot4a = plot(rbind(amces4a, diff_amces4a)) + ggplot2::facet_wrap(~BY, ncol = 3L) + ggtitle("") + theme(plot.title = element_text(hjust = 0.5)) + geom_point(size = 3) + scale_y_discrete(labels=c("(Speed corruption)"="SPEED CORRUPTION","(Theft corruption)"="THEFT CORRUPTION")) + theme(text = element_text(size = 25))

#######################################
# Results
#######################################

# Figure 1
plot4a = plot(rbind(amces4a, diff_amces4a)) + ggplot2::facet_wrap(~BY, ncol = 3L) + scale_y_discrete(labels=c("(Speed corruption)"="SPEED CORRUPTION","(Theft corruption)"="THEFT CORRUPTION"))
ggsave('figure1.pdf', plot4a, width = 20, height = 10)

# Tables A3-A5
cj(d, outcome_q3 ~ speed_eng + theft_eng  + partyid_eng + age_eng + education_eng, id = ~idnum, estimate = "amce", by = ~gender_eng)
cj(d, outcome_q3 ~ speed_eng + theft_eng + partyid_eng + age_eng + education_eng, id = ~idnum, estimate = "amce_diff", by = ~gender_eng)

